<template lang="html">
  <div class="layout">
        <Alert banner closable type="warning" style="margin-bottom: 0;text-align: center;">
          <span v-show="guest">亲爱的{{guest.reginName}}-{{guest.city}} 用户，您是第{{guest.rank}}名访问本站！</span>
          本系统处于测试阶段，如果遇到什么问题请提交<a href="https://gitee.com/sma2lbao/website/issues" target="_blank">Issue</a>！我将尽快修复。
        </Alert>
        <Layout>
            <Header>
                <Menu ref="mianMenu" mode="horizontal" theme="dark" :active-name="activeMenu"
                  :style="{height: '64px', lineHeight: '64px'}">
                    <div class="layout-logo"></div>
                    <div class="layout-nav">
                        <router-link :to="{ name: 'Main' }">
                          <MenuItem name="Main">
                            <Icon type="ios-home"></Icon>
                            首页
                          </MenuItem>
                        </router-link>
                        <router-link :to="{ name: 'BlogMenu' }">
                          <MenuItem name="Blog">
                            <Icon type="ios-paper"></Icon>
                            博客
                          </MenuItem>
                        </router-link>
                        <router-link :to="{ name: 'MusciMenu' }">
                          <MenuItem name="Music">
                            <Icon type="ios-musical-notes"></Icon>
                            音乐
                          </MenuItem>
                        </router-link>
                        <!-- <MenuItem name="3" >
                            <Icon type="ios-analytics"></Icon>
                            音乐
                        </MenuItem>
                        <MenuItem name="4">
                            <Icon type="ios-paper"></Icon>
                            视频
                        </MenuItem> -->
                    </div>

                    <div class="layout-head-tool">
                      <a :style="{color: '#fff'}" v-if="!loggedIn" @click="handleShowModal">登录 | 注册</a>

                      <Dropdown @on-click="handleLogout" v-if="loggedIn">
                        <Avatar v-if="photoUrl" :src="photoUrl"/>
                        <Avatar v-else>
                          {{ username.substring(0, 1) }}
                        </Avatar>
                        <DropdownMenu slot="list">
                          <DropdownItem name="logout">退出登录</DropdownItem>
                        </DropdownMenu>
                      </Dropdown>
                    </div>
                </Menu>
            </Header>
            <Content :style="{margin: '10px 20px 0', minHeight: '500px'}">
              <router-view></router-view>
            </Content>
            <Footer class="layout-footer-center">
              <FooterDetail />
            </Footer>
        </Layout>

        <Modal v-model="showModal">
            <!-- <p slot="header" style="color:#f60;text-align:center">
                <Icon type="information-circled"></Icon>
                <span>Delete confirmation</span>
            </p> -->
            <Row :style="{width: 'calc(100% - 20px)', position: 'relative'}">
              <div class="modal-wrap">
                <img width="80%" src="http://sma2lbao.gitee.io/static/img/logo.png" />
              </div>
              <Col span="12" offset="12">
                <Tabs>
                  <TabPane label="登录">
                    <Form ref="loginForm" :model="login" :rules="loginRule" >
                      <FormItem prop="name" >
                        <Input v-model="login.name" type="text" placeholder="用户名">
                          <Icon type="ios-person-outline" slot="prepend"></Icon>
                        </Input>
                      </FormItem>
                      <FormItem prop="password">
                        <Input v-model="login.password" type="password" placeholder="密码">
                          <Icon type="ios-locked-outline" slot="prepend"></Icon>
                        </Input>
                      </FormItem>

                      <FormItem prop="verity">
                        <Input v-model="login.verity" type="text" placeholder="验证码" :style="{width: '100px'}"></Input>
                        <img ref="loginVerity" src="/getVerify" :style="{verticalAlign: 'middle', cursor: 'pointer'}" @click="handleRefreshVerity($event.target)" />
                      </FormItem>

                      <FormItem>
                        <Button @click="handleLogin('loginForm')" type="primary" long>登录</Button>
                      </FormItem>
                    </Form>
                  </TabPane>
                  <TabPane label="注册">
                    <Form ref="regForm" :model="reg" :rules="regRule">
                      <FormItem prop="name">
                        <Input v-model="reg.name" type="text" placeholder="用户名">
                          <Icon type="ios-person-outline" slot="prepend"></Icon>
                        </Input>
                      </FormItem>
                      <FormItem prop="password">
                        <Input ref="regPassIpt" v-model="reg.password" :type="reg.showPass ? 'text': 'password'" placeholder="密码">
                          <Icon type="ios-locked-outline" slot="prepend"></Icon>
                          <Button v-if="reg.showPass" slot="append" icon="eye-disabled" @click="reg.showPass = false"></Button>
                          <Button v-else slot="append" icon="eye" @click="reg.showPass = true"></Button>
                        </Input>
                      </FormItem>
                      <FormItem prop="email">
                        <Input v-model="reg.email" type="text" placeholder="邮箱">
                          <Icon type="ios-email-outline" slot="prepend"></Icon>
                        </Input>
                      </FormItem>

                      <FormItem>
                        <Button @click="handleReg('regForm')" type="primary" long>注册</Button>
                      </FormItem>
                    </Form>
                  </TabPane>
                </Tabs>
              </Col>
            </Row>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'Vuex'
import FooterDetail from './components/FooterDetail.vue'

export default {
  name: 'App',
  data () {
    return {
      verityImg: '',
      guest: {},
      // activeMenu: 'Main',
      showModal: false, //是否弹出登录/注册窗口
      login: {
        name: '',
        password: '',
        verity: '',
      },
      loginRule: {
        name: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
        ],
        verity: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ],
      },
      reg: {
        name: '',
        password: '',
        email: '',
        showPass: false,
      },
      regRule: {
        name: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/, message: '需字母开头可带数字、“_”、“.”', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { pattern: /^(\w|\S){6,20}$/, message: '只能是6-20个字母、数字、特殊字符', trigger: 'blur'}
        ],
        email: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { type: 'email', message: 'Incorrect email format', trigger: 'blur' }
        ]
      },
    }
  },
  components: { FooterDetail },
  computed: {
    ...mapState([
      'activeMenu',
      'loggedIn',
      'photoUrl',
      'username',
    ])
  },
  methods: {
    ...mapActions(['saveGuest', 'queryGuestInfo', 'checkVerityAsync']),
    ...mapMutations([ 'changeMenu', 'changeLogin', 'logout' ]),
    handleShowModal () {
      this.showModal = true
    },
    handleLogin (formName) {
      this.$refs[formName].validate(async(valid) => {
          if (valid) {
              const isVerity = await this.checkVerityAsync(this.login.verity)
              console.log(isVerity)
              if (!isVerity) {
                this.$Message.error('验证码错误')
                this.login.verity = ''
                this.handleRefreshVerity(this.$refs.loginVerity)
                return
              }
              this.login.verity = ''
              this.handleRefreshVerity(this.$refs.loginVerity)

              this.$store.dispatch('accessTokenAsync', {username: this.login.name, password: this.login.password})
                .then(res => {
                  if(res.data) {
                    this.showModal = false
                    // 改变登录状态值
                    this.changeLogin({
                      loggedIn: true,
                      username: this.login.name,
                      access_token: res.data.access_token
                    })
                    // 设置基本信息
                    this.$store.dispatch('setUserInfoByUsername', this.login.name)
                    this.$Message.success('登录成功')
                    this.login = {
                      name: '',
                      password: ''
                    }
                  } else {
                    this.$Message.error('用户名或密码错误')
                  }
                })
          } else {
              this.$Message.error('验证失败')
          }
      })
    },

    handleLogout (name) {
      if (name = 'logout') {
        this.$Message.info('用户已退出登录')
        this.logout() // 改变登录状态值
      }
    },

    handleReg (formName) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$store.dispatch('regAsync', {
              name: this.reg.name,
              password: this.reg.password,
              email: this.reg.email
            }).then(async (res) => {
              if(res.data) {
                this.showModal = false
                const {data: tokenData} = await this.$store.dispatch('accessTokenAsync', {username: this.reg.name, password: this.reg.password})
                if(tokenData) {
                  // 改变登录状态值
                  this.changeLogin({
                    loggedIn: true,
                    username: this.reg.name,
                    access_token: tokenData.access_token
                  })
                  this.$store.dispatch('setUserInfoByUsername', this.reg.name)
                } else {
                  this.$Message.error('获取token错误')
                }

                this.$Message.success('注册成功')
                this.reg = {
                  name: '',
                  password: '',
                  email: '',
                }
              }
            })
            .catch(err => {
              if (err.response) {
                console.log('response', err.response);
                if (err.response.status === 409) {
                  this.$Message.error('用户名已存在');
                }
              } else if (err.request) {
                console.log('request', err.request);
              } else {
                console.log('err', err);
              }
            })

          } else {
              this.$Message.error('验证失败');
          }
      })
    },

    async handleGuest() {
      // 保存用户信息
      await this.saveGuest()
      const guest = await this.queryGuestInfo()
      this.guest = guest
    },

    // 刷新验证码
    handleRefreshVerity (dom) {
      dom.src = '/getVerify?' + Math.random()
    },
  },

  watch: {
    '$route' (val) {
      if (val.name === 'BlogDetail') {
        this.$refs.mianMenu.currentActiveName = 'Blog'
      }
    }
  },
  beforeMount () {
    this.$Loading.start()
    const { name: routeName } = this.$route
    switch (routeName) {
      case 'Main':
        this.changeMenu({activeMenu: 'Main'});
        break;
      case 'BlogMenu':
        this.changeMenu({activeMenu: 'Blog'});
        break;
      case 'BlogList':
        this.changeMenu({activeMenu: 'Blog'});
        break;
      case 'BlogDetail':
        this.changeMenu({activeMenu: 'Blog'});
        break;
      case 'BlogCreation':
        this.changeMenu({activeMenu: 'Blog'});
        break;
      case 'MusciMenu':
        this.changeMenu({activeMenu: 'Music'})
        break;
      default:
        this.changeMenu({activeMenu: 'Main'});
    }
  },
  mounted () {
    setTimeout(() => {
      this.$Loading.finish()
    }, 1000)
    // 保存用户信息
    this.handleGuest()
  },
  destroyed () {
    console.log('destroyed');
  }
}
</script>

<style lang="css" scoped>
    .layout{
        background: #f5f7f9;
        position: relative;
        overflow: hidden;
    }
    .layout-logo{
        width: 200px;
        height: 64px;
        border-radius: 3px;
        float: left;
        position: relative;
        top: 0;
        background: url('http://sma2lbao.gitee.io/static/img/logo-white.png') no-repeat center center;
        background-size: contain;
    }
    .layout-nav{
        float: left;
    }
    .layout-head-tool{
      position: absolute;
      right: 0;
      top: 50%;
      transform: translate(0, -50%);
      line-height: 0;
    }
    .layout-footer-center{
        text-align: center;
        background-color: #495060;
        color: #fff;
        margin-top: 20px;
    }
    .modal-wrap {
      width: calc(50% - 10px);
      position: absolute;
      top: 50%;
      left: 0;
      transform: translate(0, -50%);
    }
</style>
